package com.example.xunai.service.mq;

import com.example.xunai.dto.request.ai.ChatRequest;
import com.example.xunai.dto.response.ai.ChatResponse;
import com.example.xunai.config.RabbitMQConfig;
import com.example.xunai.service.cache.CacheService;
import com.example.xunai.service.ai.AiChatService;
import com.example.xunai.service.ai.BatchChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class AiProcessConsumer {

    private final AiChatService aiChatService;
    private final CacheService cacheService;
    private final RabbitTemplate rabbitTemplate;
    private final BatchChatService batchChatService;
    private static final int MAX_RETRY_COUNT = 3;
    private static final int MAX_BATCH_RETRY_COUNT = 2;

    @RabbitListener(queues = RabbitMQConfig.AI_PROCESS_QUEUE)
    public void processAiRequest(Object request) {
        log.info("开始处理AI请求: {}", request);

        try {
            // 从request对象中提取必要信息
            ChatRequest chatRequest = ChatRequest.of(
                    getMessageFromRequest(request),
                    getSessionIdFromRequest(request),
                    getConversationIdFromRequest(request),
                    getUserIdFromRequest(request),
                    getModelTypeFromRequest(request)
            );

            // 使用新的方法获取ChatResponse
            ChatResponse response = aiChatService.getAiResponse(chatRequest);

            if (response != null && response.getContent() != null && !response.getContent().trim().isEmpty()) {
                // 缓存响应结果
                String requestId = getRequestIdFromRequest(request);
                cacheService.cacheAiResponse(requestId, response.getContent());
                cacheService.cacheRequestStatus(requestId, "COMPLETED");

                log.info("AI请求处理完成: {}, 内容长度: {}", requestId, response.getContent().length());
            } else {
                handleProcessFailure(request, "AI响应为空");
            }

        } catch (Exception e) {
            log.error("处理AI请求失败", e);
            handleProcessFailure(request, e.getMessage());
        }
    }

    /**
     * 批量处理AI请求
     */
    @RabbitListener(queues = RabbitMQConfig.AI_BATCH_PROCESS_QUEUE)
    public void processBatchAiRequest(List<Object> requests) {
        log.info("开始批量处理AI请求，数量: {}", requests.size());

        try {
            List<ChatRequest> chatRequests = new ArrayList<>();
            for (Object request : requests) {
                ChatRequest chatRequest = ChatRequest.of(
                        getMessageFromRequest(request),
                        getSessionIdFromRequest(request),
                        getConversationIdFromRequest(request),
                        getUserIdFromRequest(request),
                        getModelTypeFromRequest(request)
                );
                chatRequests.add(chatRequest);
            }

            // 使用批量服务处理
            List<String> responses = batchChatService.batchChat(chatRequests);

            // 处理每个响应
            for (int i = 0; i < requests.size(); i++) {
                Object request = requests.get(i);
                String response = responses.get(i);

                if (response != null && !response.trim().isEmpty() && !response.startsWith("处理失败")) {
                    String requestId = getRequestIdFromRequest(request);
                    cacheService.cacheAiResponse(requestId, response);
                    cacheService.cacheRequestStatus(requestId, "COMPLETED");
                    log.info("批量AI请求处理完成: {}", requestId);
                } else {
                    handleBatchProcessFailure(request, "AI响应无效: " + response);
                }
            }

            log.info("批量AI请求处理完成，总数: {}", requests.size());

        } catch (Exception e) {
            log.error("批量处理AI请求失败", e);
            for (Object request : requests) {
                handleBatchProcessFailure(request, e.getMessage());
            }
        }
    }

    // 需要您根据实际的请求对象实现这些方法
    private String getMessageFromRequest(Object request) {
        if (request instanceof Map) {
            Object message = ((Map<?, ?>) request).get("message");
            if (message instanceof String) {
                return (String) message;
            }
        }
        return "";
    }

    private String getSessionIdFromRequest(Object request) {
        if (request instanceof Map) {
            Object sessionId = ((Map<?, ?>) request).get("sessionId");
            if (sessionId instanceof String) {
                return (String) sessionId;
            }
        }
        return "";
    }

    private Long getConversationIdFromRequest(Object request) {
        if (request instanceof Map) {
            Object conversationId = ((Map<?, ?>) request).get("conversationId");
            if (conversationId instanceof Long) {
                return (Long) conversationId;
            } else if (conversationId instanceof Integer) {
                return ((Integer) conversationId).longValue();
            } else if (conversationId instanceof String) {
                try {
                    return Long.parseLong((String) conversationId);
                } catch (NumberFormatException e) {
                    return null;
                }
            }
        }
        return null;
    }

    private Long getUserIdFromRequest(Object request) {
        if (request instanceof Map) {
            Object userId = ((Map<?, ?>) request).get("userId");
            if (userId instanceof Long) {
                return (Long) userId;
            } else if (userId instanceof Integer) {
                return ((Integer) userId).longValue();
            } else if (userId instanceof String) {
                try {
                    return Long.parseLong((String) userId);
                } catch (NumberFormatException e) {
                    return 1L;
                }
            }
        }
        return 1L;
    }

    private String getModelTypeFromRequest(Object request) {
        if (request instanceof Map) {
            Object modelType = ((Map<?, ?>) request).get("modelType");
            if (modelType instanceof String) {
                return (String) modelType;
            }
        }
        return "deepseek";
    }

    private String getRequestIdFromRequest(Object request) {
        if (request instanceof Map) {
            Object requestId = ((Map<?, ?>) request).get("requestId");
            if (requestId instanceof String) {
                return (String) requestId;
            }
        }
        return String.valueOf(System.currentTimeMillis());
    }

    private void handleProcessFailure(Object request, String error) {
        String requestId = getRequestIdFromRequest(request);
        if (getRetryCountFromRequest(request) < MAX_RETRY_COUNT) {
            // 重试逻辑
            log.info("AI请求进入重试队列: {}, 错误: {}", requestId, error);
        } else {
            // 最终失败
            cacheService.cacheRequestStatus(requestId, "FAILED");
            cacheService.cacheAiResponse(requestId, "处理失败: " + error);
            log.error("AI请求最终失败: {}, 错误: {}", requestId, error);
        }
    }

    private void handleBatchProcessFailure(Object request, String error) {
        String requestId = getRequestIdFromRequest(request);
        if (getRetryCountFromRequest(request) < MAX_BATCH_RETRY_COUNT) {
            // 重试逻辑
            log.info("批量AI请求进入重试队列: {}, 错误: {}", requestId, error);
        } else {
            // 最终失败
            cacheService.cacheRequestStatus(requestId, "FAILED");
            cacheService.cacheAiResponse(requestId, "处理失败: " + error);
            log.error("批量AI请求最终失败: {}, 错误: {}", requestId, error);
        }
    }

    private int getRetryCountFromRequest(Object request) {
        if (request instanceof Map) {
            Object retryCount = ((Map<?, ?>) request).get("retryCount");
            if (retryCount instanceof Integer) {
                return (Integer) retryCount;
            }
        }
        return 0;
    }
}